<?php

namespace app\controller\common;

use app\BaseController;
use app\Code;
use app\common\JWTUtils;
use app\dao\UserDao;
use app\model\MemberModel;
use app\model\UserModel;
use app\validate\LoginValidate;
use think\exception\ValidateException;
use think\facade\Request;

class AuthController extends BaseController
{
    // 用户登录
    public function login()
    {
        // 获取请求参数
        $data = Request::only(['username', 'password']);

        // 验证请求参数
        try {
            validate(LoginValidate::class)->scene('login')->check($data);
        } catch (ValidateException $e) {
            // 返回错误信息
            return $this->returnJson([], Code::UNPROCESSABLE_ENTITY, $e->getMessage());
        }

        // 根据用户名获取用户信息
        $user = (new UserDao)->getUserByUsername($data['username']);

        // 验证用户名和密码是否正确
        if ($user && password_verify($data['password'], $user->password)) {

            // 使用 JWTUtils 生成 Token
            $token = JWTUtils::encode($user->id, $user->username, $user->role);

            // 查找 member_id（如果是学生）
            $memberId = null;
            if ($user->role === UserModel::ROLE_STUDENT) {
                $member = MemberModel::where('user_id', $user->id)->find();
                if ($member) {
                    $memberId = $member->id;
                }
            }

            // 返回用户信息
            return $this->returnJson([
                'id' => $user->id,
                'username' => $user->username,
                'real_name' => $user->real_name,
                'role' => $user->role,
                'member_id' => $memberId,
                'token' => $token,
            ]);
        }

        // 返回错误信息
        return $this->returnJson([], Code::UNAUTHORIZED, '用户名或密码错误');
    }


    // 用户登出
    public function logout()
    {
        jwt(null); // 清除会话
        return $this->returnJson();
    }
}
